﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.Contract;
using MaxLeaf.Platform.DALImplementation;
using MaxLeaf.Platform.DataContract;
using CommonsLib.Utility;
using CommonsLib.Settings;
using MaxLeaf.Platform.Functions;
using MaxLeaf.Platform.BRL;
using MaxLeaf.Platform.Commons;
using CommonsLib.DB;
using System.Data.SqlClient;

namespace MaxLeaf.Platform.BLLImplementation
{
    public class mUser_MainBLL :BaseBLL, IUser
    {
         

        #region IUser 成员

        public mUser_MainDataModel Login(string strUserName, string strPassword)
        {
            int intKeyValue = ((mUser_MainDAL)this.CurrentDAL).Login(strUserName, HashPWD(strPassword));
            if( intKeyValue==0)
            {
                return null;
            }

            return (mUser_MainDataModel)this.Select(new mUser_MainDataModel(), intKeyValue);
        }

        public bool ResetPassword(string strUserName, string strOldPassword, string strNewPassword)
        {
            bool blnRT = ((mUser_MainDAL)this.CurrentDAL).ResetPassword(strUserName, (strOldPassword.Length==0?string.Empty:HashPWD(strOldPassword)), HashPWD(strNewPassword));
            if (blnRT)
            {
                try {
                    using (DBAccess dbcon = DataFunc.GetDBAccessByDataModelType(typeof(mUser_MainDataModel)))
                    {
                        object company = BaseBLL.GetDataModelBLL("mCompanyDataModel").Select(new mCompanyDataModel(),CvtFunc.ToInt(
                               dbcon.GetValue("selet companyid from mUser_Main  where  UserName=@UserName",new SqlParameter[]{
                                   new SqlParameter("@UserName",strUserName)
                               })
                            ));
                        new mCompanyBLL().Update_Web(dbcon, company);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error(ex);
                }
            }

            return blnRT;
            
        }
        #endregion

        private string HashPWD(string strPassword)
        {
            return MD5Func.Hash(PREFIX_PWD + strPassword);
        }
        private const string PREFIX_PWD ="";// "jhR9$8";

        public override object Add(object model)
        {
            mUser_MainDataModel user = model as mUser_MainDataModel;
            user.PassWord = HashPWD(user.PassWord);

             
            return base.Add(user);
        }

        public override string FinterIDFields
        {
            get
            {
                return string.Format("{0},{1}", "UserID", (int)FinterIDType.User);
            }
        }
       
    }
}
